package database;

import java.util.*;
import java.sql.*;


public class ConnectionPool {
  private static ConnectionPool connectionPool = null;  

  private Vector<Connection> freeConnections; 
  private String dbUrl;        
  private String dbDriver;     
  private String dbUser;     
  private String dbPassword;    

  ConnectionPool() throws ConnectionPoolException {
    freeConnections = new Vector<Connection>();  
    loadParameters();               
    loadDriver();                    
  }

  private void loadParameters() {
    dbUrl = "jdbc:mysql://localhost/mirc";  
    dbDriver = "com.mysql.jdbc.Driver";   
    dbUser = "mirc"; 
    dbPassword = "mirc"; 
  }

  private void loadDriver() throws ConnectionPoolException {
    try {
      java.lang.Class.forName(dbDriver);
    }
    catch (Exception e) {
      throw new ConnectionPoolException();
    }
  }

  public static synchronized ConnectionPool getConnectionPool() 
  throws ConnectionPoolException {
    if(connectionPool == null) {
      connectionPool = new ConnectionPool();
    }
    return connectionPool;
  }

  public synchronized Connection getConnection() throws ConnectionPoolException {
	  Connection con;

	  if(freeConnections.size() > 0) {      
		  con = (Connection)freeConnections.firstElement();  
		  freeConnections.removeElementAt(0);                
		  try {
			  if(con.isClosed()) {          
				  con = getConnection(); 
			  }
		  }
		  catch(SQLException e) { 
			  con = getConnection(); 
		  }
	  }
	  else {
		  con = newConnection();    
	  }
	  return con;
  } 

  private Connection newConnection() throws ConnectionPoolException {
    Connection con = null;
      
    try {
      con = DriverManager.getConnection(dbUrl,dbUser,dbPassword); 
    }catch(SQLException e) {                      
      throw new ConnectionPoolException();       
    }
    return con;                                 
  }

  public synchronized void releaseConnection(Connection con) {
    freeConnections.add(con); 
  }
}
